const Role = require('./role');

class Team {
    constructor(server, option, creator) {
        this.server = server;
        this.option = option;
        this.size = this.server.config.team.size;
        this.roles = new Array(this.size).fill(creator || true, 0, 1).fill(true, 1);
    }
    add(role) {
        if (this.roles[role.index] === true) {
            this.roles[role.index] = role;
        } else {
            throw '';
        }
    }
    remove(role) {
        if (this.roles[role.index] === role) {
            this.roles[role.index] = true;
        } else {
            throw '';
        }
    }
    dispose() {
        this.roles.forEach(role => role instanceof Role && delete role.player.room);
        this.roles = new Array(this.size).fill(true);
    }
    get count() {
        return this.roles.filter(role => role instanceof Role).length;
    }
    get emptyIndex() {
        return this.roles.findIndex(role => role === true);
    }
    get emptyCount() {
        return this.roles.filter(role => role === true).length;
    }
    get openCount() {
        return this.roles.filter(role => role !== false).length;
    }
    get data() {
        return {
            name: this.option.name,
            color: this.option.color,
            icon: this.option.icon,
            roles: this.roles.map(role => role instanceof Role ? role.data : role)
        }
    }
    static create(server, option, creator) {
        return new (server.config.Team || Team)(server, option, creator);
    }
    static createTeams(server, creator) {
        let teams = server.config.teams;
        if (teams && teams.length) {
            return [ Team.create(server, teams[0], creator), ...teams.slice(1).map(team => Team.create(server, team)) ];
        } else {
            return [ Team.create(server, { }, creator) ];
        }
    }
}

module.exports = Team;